package com.base.common;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Encoder;

public class DesUtil
{
  public static byte[] encrypt(byte[] rawKeyData, String str)
    throws Exception
  {
    System.out.println(str);

    SecureRandom sr = new SecureRandom();

    DESKeySpec dks = new DESKeySpec(rawKeyData);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);

    Cipher cipher = Cipher.getInstance("DES");

    cipher.init(1, key, sr);

    byte[] data = str.getBytes();

    byte[] encryptedData = cipher.doFinal(data);

    System.out.println("加密后===>" + encryptedData);
    return encryptedData;
  }

  public static String decrypt(byte[] rawKeyData, byte[] encryptedData)
    throws Exception
  {
    SecureRandom sr = new SecureRandom();

    DESKeySpec dks = new DESKeySpec(rawKeyData);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);

    Cipher cipher = Cipher.getInstance("DES");

    cipher.init(2, key, sr);

    byte[] decryptedData = cipher.doFinal(encryptedData);
    System.out.println("解密后===>" + new String(decryptedData));
    return new String(decryptedData);
  }

  public static void main(String[] args)
    throws Exception
  {
    byte[] rawKeyData = "yzP2r42=".getBytes("UTF-8");

    String str = "2010-07-20 18:38abcdeffedcba";

    byte[] encryptedData = encrypt(rawKeyData, str);
    BASE64Encoder be = new BASE64Encoder();
    System.out.println(be.encode(encryptedData));

    String i = decrypt(rawKeyData, encryptedData);
  }
}
